﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Navigant.Infrastructure.Cases;
using Navigant.Model.Cases;
using Navigant.Model.PreservationNotices;
using System.Data;
using Navigant.Infrastructure.Helpers;

namespace Navigant.Web.UI
{
    public class PreservationNoticeHistoryWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        private EnhancedSPGridView grid;
        private Button exportButton;
        private int pageSize;
        private string preservationNoticeQueryString;

        private const int DefaultPageSize = 15;

        public PreservationNoticeHistoryWebPart()
        {
            this.pageSize = DefaultPageSize;
            this.preservationNoticeQueryString = string.Empty;
        }

        [Browsable(true), Category("Data"), DefaultValue(DefaultPageSize),
        WebPartStorage(Storage.Shared), FriendlyName("Page Size")]
        public int PageSize
        {
            get { return this.pageSize; }
            set { this.pageSize = value; }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.exportButton = new Button();
            this.exportButton.Text = "Export to CSV";
            this.exportButton.Click += new EventHandler(this.exportButton_Click);
            this.Controls.Add(this.exportButton);
            this.grid = new EnhancedSPGridView();
            this.grid.ID = this.ID + "-grid";
            this.grid.RequiresDataSource += new EventHandler(this.grid_RequiresDataSource);
            this.grid.AutoGenerateColumns = false;
            this.grid.EnableTheming = true;

            // Turn on paging and add event handler
            this.grid.PageSize = this.pageSize;
            this.grid.AllowPaging = true;
            //this.grid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
            //this.grid.PagerSettings.NextPageImageUrl = "/_layouts/images/ewr020.gif";
            //this.grid.PagerSettings.FirstPageImageUrl = "/_layouts/images/ewr018.gif";
            //this.grid.PagerSettings.PreviousPageImageUrl = "/_layouts/images/ewr019.gif";
            //this.grid.PagerSettings.LastPageImageUrl = "/_layouts/images/ewr021.gif";
            this.grid.PageIndexChanging += new GridViewPageEventHandler(this.grid_PageIndexChanging);

            this.grid.Columns.Clear();

            TemplateField templateName = new TemplateField();
            //templateName.DataField = "Template";
            templateName.ItemTemplate = new PreservationNoticeGridViewTemplate(DataControlRowType.DataRow);
            templateName.HeaderText = "Preservation Notice Name";
            this.grid.Columns.Add(templateName);

            SPBoundField status = new SPBoundField();
            status.DataField = "Status";
            status.HeaderText = "Status";
            this.grid.Columns.Add(status);

            SPBoundField to = new SPBoundField();
            to.DataField = "To";
            to.HeaderText = "Custodian";
            this.grid.Columns.Add(to);

            TemplateField custodianEmail = new TemplateField();
            custodianEmail.ItemTemplate = new CustodianEmailTemplateField(DataControlRowType.DataRow);
            custodianEmail.HeaderText = "Custodian Email";
            this.grid.Columns.Add(custodianEmail);

            SPBoundField fromAddress = new SPBoundField();
            fromAddress.DataField = "FromAddress";
            fromAddress.HeaderText = "From Address";
            this.grid.Columns.Add(fromAddress);

            SPBoundField subject = new SPBoundField();
            subject.DataField = "Subject";
            subject.HeaderText = "Message Subject";
            this.grid.Columns.Add(subject);

            SPBoundField dateQueued = new SPBoundField();
            dateQueued.DataField = "DateMessageCreated";
            dateQueued.HeaderText = "Date Queued";
            this.grid.Columns.Add(dateQueued);

            SPBoundField dateSent = new SPBoundField();
            dateSent.DataField = "DateMessageSent";
            dateSent.HeaderText = "Date Sent";
            this.grid.Columns.Add(dateSent);

            SPBoundField dateAcknowledged = new SPBoundField();
            dateAcknowledged.DataField = "DateMessageAcknowledged";
            dateAcknowledged.HeaderText = "Date Acknowledged";
            this.grid.Columns.Add(dateAcknowledged);

            // Add grouping to the grid
            //this.grid.AllowGrouping = true;
            //this.grid.AllowGroupCollapse = true;
            //this.grid.GroupField = "To";
            //this.grid.GroupDescriptionField = "To";
            //this.grid.GroupFieldDisplayName = "Custodian";
            
            this.Controls.Add(this.grid);
        }

        private void grid_RequiresDataSource(object sender, EventArgs e)
        {
            this.grid.DataBind();
        }

        private void exportButton_Click(object sender, EventArgs e)
        {
            this.ExportPreservationNoticeHistoryToCsv();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.preservationNoticeQueryString = this.Page.Request.QueryString["PreservationNoticeHistoryID"];
            this.EnsureChildControls();
            if (!this.Page.IsPostBack)
            {
                // Current page index will be set to when page 
                // is opened for the first time
                this.BindGrid(1);
            }
        }

        private void ExportPreservationNoticeHistoryToCsv()
        {
            // Get the PN history for the site
            SPWeb web = SPControl.GetContextWeb(HttpContext.Current);
            ICase currentCase = CaseService.GetCaseBy(new Uri(web.Url));
            PreservationNoticeService service = new PreservationNoticeService(currentCase);
            DataTable historyItems = service.GetPreservationNoticesBySiteRaw();

            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment;filename=pnhistory.csv");

            // Write out the headers
            response.Write("Hist ID,Event Type,Preservation Notice ID,PN Name,Created,Sent,Acknowledged,To,Last,First");
            response.Write("\r\n");

            // Iterate the list to add the rows
            foreach (DataRow historyItem in historyItems.Rows)
            {
                response.Write(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\"",
                    DataHelper.GetString(historyItem["PreservationNoticeHistoryID"]),
                    DataHelper.GetEnumValue<PreservationNoticeStatus>(historyItem["EventType"]),
                    DataHelper.GetString(historyItem["PreservationNoticeID"]),
                    DataHelper.GetString(historyItem["PreservationNoticeName"]),
                    DataHelper.GetString(historyItem["DateEmailMessageCreated"]),
                    DataHelper.GetString(historyItem["DateEmailMessageSent"]),
                    DataHelper.GetString(historyItem["DateAcknowledged"]),
                    DataHelper.GetString(historyItem["CustodianEmail"]),
                    DataHelper.GetString(historyItem["CustodianLastName"]), 
                    DataHelper.GetString(historyItem["CustodianFirstName"])));
                response.Write("\r\n");
            }
            response.End();
        }

        private void BindGrid(int currentPageIndex)
        {
            SPWeb web = SPControl.GetContextWeb(HttpContext.Current);
            ICase currentCase = CaseService.GetCaseBy(new Uri(web.Url));
            PreservationNoticeService service = new PreservationNoticeService(currentCase);
            IList<PreservationNotice> historyItems = null;
            int itemCount = 0;
                        
            if (string.IsNullOrEmpty(this.preservationNoticeQueryString))
            {
                //historyItems = service.GetPreservationNoticesBySite();
                historyItems = service.GetPreservationNoticesBySite(this.pageSize,
                    currentPageIndex, out itemCount);
            }
            else
            {
                historyItems = new List<PreservationNotice>(); 
                historyItems.Add(service.GetPreservationNotice(int.Parse(this.preservationNoticeQueryString)));
            }

            this.grid.DataSource = historyItems;
            this.grid.PagerTemplate = null;
            this.grid.VirtualItemCount = itemCount;
            
            // Bind the grid
            this.grid.DataBind();
        }

        private void grid_PageIndexChanging(object sender, 
            GridViewPageEventArgs e)
        {
            this.EnsureChildControls();
            this.grid.PageIndex = e.NewPageIndex;
            // Need to add 1 to account for the grid
            // paging being base 0 and the 
            // server-side paging being base 1
            this.BindGrid(this.grid.PageIndex + 1);
        }
    }
}